import { ref,reactive } from 'vue'
import { defineStore } from 'pinia'
import axios from "axios";

interface CommonRecodeData {
  id: number
  create_time: any
  update_time: any
  device_series_id: string
  name: string
  value: string
  times_tamp: any
}

export const useCounterStore = defineStore('useCounterStore', () => {


  const refreshFlag = ref(false)
  const token = ref('')
  const nowData = ref<Record<string, CommonRecodeData>>({
    "327061430532576250": {} as CommonRecodeData,
    "327061430532576241": {} as CommonRecodeData,
    "327061430532576242": {} as CommonRecodeData,
    "327061430532576243": {} as CommonRecodeData,
    "327061430532576244": {} as CommonRecodeData,
    "327061430532576245": {} as CommonRecodeData,
  })

  const getNowData = async () => {
    try {
      const response = await axios.get<Record<string, CommonRecodeData>>('/api/data/common-device', {
        headers: { 'Authorization': token.value }
      })

      for (const key in response.data) {
        if (response.data.hasOwnProperty(key) && nowData.value.hasOwnProperty(key)) {
          nowData.value[key] = {
            id: response.data[key].id,
            create_time: response.data[key].create_time,
            update_time: response.data[key].update_time,
            device_series_id: response.data[key].device_series_id,
            name: response.data[key].name,
            value: response.data[key].value,
            times_tamp: response.data[key].times_tamp,
          }
          console.log(nowData.value)
        }
      }
    } catch (error) {
      console.log(error)
    }
  }

  const historyData = ref({
    "327061430532576250": [] as CommonRecodeData[],
    "327061430532576241": [] as CommonRecodeData[],
    "327061430532576242": [] as CommonRecodeData[],
    "327061430532576243": [] as CommonRecodeData[],
    "327061430532576244": [] as CommonRecodeData[],
    "327061430532576245": [] as CommonRecodeData[],
  })
  const getHistoryData = async (deviceId: string) => {
    try {
      const response = await axios.get<CommonRecodeData[]>('/api/data/common-history', {
        headers: { 'Authorization': token.value },
        params: {"seriesId": deviceId}
      })
      if (historyData.value.hasOwnProperty(deviceId)) {
        historyData.value[deviceId] = []
        for (const item of response.data){
          let tempData : CommonRecodeData = {
            id: item.id,
            create_time: item.create_time,
            update_time: item.update_time,
            device_series_id: item.device_series_id,
            name: item.name,
            value: item.value,
            times_tamp: item.times_tamp,
          }
          historyData.value[deviceId].unshift(tempData)
        }
        console.log(historyData.value)
      }
    } catch (error) {
      console.log(error)
    }
  }

  return {
    token,
    nowData,
    historyData,
    refreshFlag,
    getNowData,
    getHistoryData
  }
})